package main

import (
	"context"
	"fmt"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"sync"
)

var ManageClient *Manage

// 客户端集合
type Manage struct {
	Cliens map[string]*Client
	Lock   sync.Mutex
	ctx    context.Context
}

// 创建客户端集合
func NewManage(ctx context.Context) *Manage {
	return &Manage{
		Cliens: make(map[string]*Client),
		Lock:   sync.Mutex{},
		ctx:    ctx,
	}
}

// 添加客户端
func (m *Manage) AddClient(client *Client) {
	m.Lock.Lock()
	defer m.Lock.Unlock()
	m.Cliens[client.Ip] = client

	//发送事件
	runtime.EventsEmit(m.ctx, "clientsAdd", client)
}

// 发送数据给客户端
func (m *Manage) SendCommand(ip string, command string) bool {
	m.Lock.Lock()
	defer m.Lock.Unlock()
	client, ok := m.Cliens[ip]
	if !ok {
		return false
	}
	err := client.Write([]byte(command))
	if err != nil {
		fmt.Printf("err : %v", err)
		return false
	}
	return true
}
